import { ElDialog, ElButton } from 'element-plus'
import { loadPlugins } from '@/main'

export const renderDialog = (component: any, props: any, dialogProps: any) => {
  const visible = ref(true)
  const instance = ref()

  const close = () => {
    visible.value = false
    setTimeout(() => {
      app.unmount()
      document.body.removeChild(div)
    }, 1000)
  }

  const dialog = () =>
    h(
      ElDialog,
      {
        ...dialogProps,
        'model-value': visible.value
      },
      {
        default: () => h(component, { ...props, ref: instance }),
        footer: dialogProps.foot
          ? () => [
              h(ElButton, { onClick: close }, () => '取消'),
              h(
                ElButton,
                {
                  type: 'primary',
                  onClick: async () => {
                    await instance.value?.submit?.()
                    close()
                  }
                },
                () => '确定'
              )
            ]
          : ''
      }
    )

  const app = createApp(dialog)
  loadPlugins(app)

  const div = document.createElement('div')
  document.body.appendChild(div)

  app.mount(div)

  return { close, instance }
}
